#!/usr/bin/python
#pingxue
#coding=utf-8
import redis
import sys;
import getopt;
import time;
def Set(r, key, value):
    r.set(key, value) 
    print(r.get(key))

def HMSet(r, key, field, value):
    r.hset(key, field, value) 
    return (r.hget(key, field))


def Connect_Redis():
    pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
    my_redis = redis.Redis(connection_pool=pool)
    return my_redis



def New_URL(r, url):
    urlcount = HMSet(r, 'siteinfo','urlcount', 0)
    for i in range(0, 200000):
        r.hincrby('siteinfo','urlcount')
        r.hset('URL:'+str(i), 'path', url)

def Expire_URL(r):
    urlcount = r.hget('siteinfo','urlcount')
    #for i in range(0, int(urlcount)):
    for i in range(0, 200000):
        r.expire('URL:arg'+str(i), 2)
def New_URL_arg(r, url):
  #  urlcount = HMSet(r, 'siteinfo','urlcount', 0)
    req_time = time.clock()
    for i in range(0, 1000):
        for j in range(0,1000):
            r.hset('URL:arg'+str(i), 'pattern.'+str(j)+'.sample_str', j)
            r.hset('URL:arg'+str(i), 'pattern.'+str(j)+'.count', j)
            r.hset('URL:arg'+str(i), 'pattern.'+str(j)+'.prob', j)
            r.hset('URL:arg'+str(i), 'pattern.'+str(j)+'.kmeans_index', j)
    res_time = time.clock()
    print((res_time-req_time)/1000000.0)

def Expire_URL_hash(r):
    for i in range(0, 1000):
        for j in range(0,1000):
            r.expire('URL:arg'+str(i)+'.'+str(j), 2)

def New_URL_arg_hash(r, url):
  #  urlcount = HMSet(r, 'siteinfo','urlcount', 0)
    req_time = time.clock()
    for i in range(0, 1000):
        for j in range(0,1000):
            r.hset('URL:arg'+str(i)+'.'+str(j), 'pattern', j)
            r.hset('URL:arg'+str(i)+'.'+str(j), 'count', j)
            r.hset('URL:arg'+str(i)+'.'+str(j), 'sample_str', j)
            r.hset('URL:arg'+str(i)+'.'+str(j), 'prob', j)
            r.hset('URL:arg'+str(i)+'.'+str(j), 'kmeans_index', j)
    res_time = time.clock()
    print((res_time-req_time)/1000000.0)



def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "cihg")
    except getopt.GetoptError:
            print("usage:\n\t-c Create Redis;\n\t")
            sys.exit(2)

    r = Connect_Redis()
    for opt,arg in opts:
        if opt == '-i':
            #New_URL(r, '/aaaabbb.html')
            New_URL_arg(r, '/test.html')
        elif opt == "-c":
            Expire_URL(r)
        elif opt == "-h":
            New_URL_arg_hash(r, '/test.html')
        elif opt == "-g":
            Expire_URL_hash(r)
        else:
            print("usage:\n\t-c Create Redis;\n\t")

if __name__ == "__main__":
    main()
